package com.tfswue.lh.listener;

import com.tfswue.lh.event.UserRegisteredEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class CustomEventListener {
    
    private static final Logger logger = LoggerFactory.getLogger(CustomEventListener.class);

    /**
     * 异步处理用户注册事件
     * 可以执行耗时操作，如发送邮件、统计分析等
     */
    @Async
    @EventListener
    public void handleUserRegistered(UserRegisteredEvent event) {
        try {
            logger.info("[异步] 自定义事件监听器开始处理用户注册: {} - {}", 
                    event.getUsername(), event.getEmail());
            
            // 模拟发送欢迎邮件
            sendWelcomeEmail(event.getUsername(), event.getEmail());
            
            // 模拟用户统计
            updateUserStatistics(event.getUsername());
            
            logger.info("[异步] 用户注册后续处理完成: {}", event.getUsername());
            
        } catch (Exception e) {
            logger.error("[异步] 处理用户注册事件失败: {}", event, e);
        }
    }
    
    /**
     * 模拟发送欢迎邮件
     */
    private void sendWelcomeEmail(String username, String email) {
        try {
            // 模拟邮件发送耗时
            Thread.sleep(1000);
            logger.info("欢迎邮件已发送至: {} ({})", username, email);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warn("邮件发送被中断");
        }
    }
    
    /**
     * 模拟更新用户统计
     */
    private void updateUserStatistics(String username) {
        try {
            // 模拟统计处理耗时
            Thread.sleep(500);
            logger.info("用户统计已更新: {}", username);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warn("统计更新被中断");
        }
    }
}